package day05.concurrent02;

/**
 * Exchanger 交换机
 */
public class Demo01 {
    private static String s = null;
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s1 = "天王盖地虎！";
                    String s2 = null;
                    synchronized (Demo01.class){
                        if(s == null){
                            s = s1;
                            Demo01.class.wait();
                            s2 = s;
                        }else{
                            s2 = s;
                            s = s1;
                            Demo01.class.notify();
                        }
                    }
                    System.out.println(Thread.currentThread()+"获取到消息:"+s2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s1 = "宝塔镇河妖！";
                    String s2 = null;
                    synchronized (Demo01.class){
                        if(s == null){
                            s = s1;
                            Demo01.class.wait();
                            s2 = s;
                        }else{
                            s2 = s;
                            s = s1;
                            Demo01.class.notify();
                        }
                    }
                    System.out.println(Thread.currentThread()+"获取到消息:"+s2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
